package com.example.authcenter.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.authcenter.mapper.UserMapper;
import com.example.authcenter.model.UserDTO;
import com.example.authcenter.utils.JwtUtils;
import com.example.common.entity.Result;
import com.example.common.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/authcenter")
@Slf4j
public class UserController {

    @Autowired(required = false)
    private UserMapper userMapper;


    @PostMapping("/auth")
    public Result auth(@RequestBody UserDTO dto){
        String token = null;
        log.info("获取参数--："+ dto);
        //查询数据库
        User user = userMapper.findByUserName(dto.getUsername());
        log.info("用户信息--："+ user);
        if (dto.getPassword().equals(user.getPassword())){
            log.info("认证通过");
            //授权生成令牌
            token = JwtUtils.generateToken();
            JSONObject data = new JSONObject();
            data.put("token",token);
            return Result.ok(data);
        }else{
            log.info("密码不错误或用户不存在");
            return Result.error("密码错误或用户不存在");
        }
    }

}
